<template>
  <div class="user-management">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>用户权限管理</h1>
          <div class="header-actions">
            <el-button type="primary" @click="showAddUserDialog">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
          </div>
        </div>
      </el-header>
      
      <el-main>
        <!-- 用户列表 -->
        <el-card class="user-list">
          <template #header>
            <span>用户列表</span>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或邮箱"
              style="width: 200px; float: right;"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </template>
          
          <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="role" label="角色">
              <template #default="scope">
                <el-tag :type="getRoleType(scope.row.role)">
                  {{ getRoleText(scope.row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                  {{ scope.row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastLogin" label="最后登录时间" />
            <el-table-column prop="createdAt" label="创建时间" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="editUser(scope.row)">
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  :type="scope.row.status === 'active' ? 'danger' : 'success'"
                  @click="toggleUserStatus(scope.row)"
                >
                  {{ scope.row.status === 'active' ? '禁用' : '启用' }}
                </el-button>
                <el-button size="small" type="danger" @click="deleteUser(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 角色权限管理 -->
        <el-card class="role-management">
          <template #header>
            <span>角色权限管理</span>
          </template>
          
          <el-table :data="roles" style="width: 100%">
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="description" label="角色描述" />
            <el-table-column label="权限">
              <template #default="scope">
                <el-tag 
                  v-for="permission in scope.row.permissions" 
                  :key="permission"
                  size="small"
                  style="margin-right: 5px;"
                >
                  {{ getPermissionText(permission) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editRole(scope.row)">
                  编辑权限
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 登录日志 -->
        <el-card class="login-logs">
          <template #header>
            <span>登录日志</span>
          </template>
          
          <el-table :data="loginLogs" style="width: 100%">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="loginTime" label="登录时间" />
            <el-table-column prop="ipAddress" label="IP地址" />
            <el-table-column prop="userAgent" label="用户代理" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                  {{ scope.row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 添加/编辑用户对话框 -->
        <el-dialog
          v-model="userDialogVisible"
          :title="isEdit ? '编辑用户' : '添加用户'"
          width="500px"
        >
          <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" :disabled="isEdit" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="!isEdit">
              <el-input v-model="userForm.password" type="password" />
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="选择角色">
                <el-option
                  v-for="role in roles"
                  :key="role.name"
                  :label="getRoleText(role.name)"
                  :value="role.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="userForm.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="userDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveUser">确定</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 编辑角色权限对话框 -->
        <el-dialog
          v-model="roleDialogVisible"
          title="编辑角色权限"
          width="600px"
        >
          <el-form :model="roleForm" ref="roleFormRef" label-width="80px">
            <el-form-item label="角色名称">
              <el-input v-model="roleForm.name" disabled />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.description" />
            </el-form-item>
            <el-form-item label="权限设置">
              <el-checkbox-group v-model="roleForm.permissions">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-checkbox value="dashboard">数据总览</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="category">分类分析</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="price">价格分析</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="query">数据查询</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="monitor">系统监控</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="user">用户管理</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="spider">爬虫控制</el-checkbox>
                  </el-col>
                  <el-col :span="12">
                    <el-checkbox value="export">数据导出</el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="roleDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveRole">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'UserManagement',
  setup() {
    const loading = ref(false)
    const searchKeyword = ref('')
    const users = ref([])
    const roles = ref([])
    const loginLogs = ref([])
    
    const userDialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const isEdit = ref(false)
    
    const userForm = reactive({
      username: '',
      email: '',
      password: '',
      role: '',
      status: 'active'
    })
    
    const roleForm = reactive({
      name: '',
      description: '',
      permissions: []
    })
    
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }

    const filteredUsers = computed(() => {
      if (!searchKeyword.value) {
        return users.value
      }
      return users.value.filter(user => 
        user.username.includes(searchKeyword.value) || 
        user.email.includes(searchKeyword.value)
      )
    })

    const fetchUsers = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/users')
        users.value = response.data
      } catch (error) {
        console.error('获取用户列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    const fetchRoles = async () => {
      try {
        const response = await axios.get('/api/roles')
        roles.value = response.data
      } catch (error) {
        console.error('获取角色列表失败:', error)
      }
    }

    const fetchLoginLogs = async () => {
      try {
        const response = await axios.get('/api/users/login-logs')
        loginLogs.value = response.data
      } catch (error) {
        console.error('获取登录日志失败:', error)
      }
    }

    const showAddUserDialog = () => {
      isEdit.value = false
      Object.keys(userForm).forEach(key => {
        userForm[key] = key === 'status' ? 'active' : ''
      })
      userDialogVisible.value = true
    }

    const editUser = (user) => {
      isEdit.value = true
      Object.keys(userForm).forEach(key => {
        if (key !== 'password') {
          userForm[key] = user[key]
        }
      })
      userDialogVisible.value = true
    }

    const saveUser = async () => {
      try {
        if (isEdit.value) {
          await axios.put(`/api/users/${userForm.username}`, userForm)
          ElMessage.success('用户更新成功')
        } else {
          await axios.post('/api/users', userForm)
          ElMessage.success('用户添加成功')
        }
        userDialogVisible.value = false
        fetchUsers()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }

    const toggleUserStatus = async (user) => {
      try {
        const newStatus = user.status === 'active' ? 'inactive' : 'active'
        await axios.patch(`/api/users/${user.username}/status`, { status: newStatus })
        ElMessage.success('状态更新成功')
        fetchUsers()
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    const deleteUser = async (user) => {
      try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await axios.delete(`/api/users/${user.username}`)
        ElMessage.success('用户删除成功')
        fetchUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const editRole = (role) => {
      Object.keys(roleForm).forEach(key => {
        roleForm[key] = role[key]
      })
      roleDialogVisible.value = true
    }

    const saveRole = async () => {
      try {
        await axios.put(`/api/roles/${roleForm.name}`, roleForm)
        ElMessage.success('角色权限更新成功')
        roleDialogVisible.value = false
        fetchRoles()
      } catch (error) {
        ElMessage.error('更新失败')
      }
    }

    const handleSearch = () => {
      // 搜索功能已通过计算属性实现
    }

    const getRoleType = (role) => {
      const types = {
        admin: 'danger',
        manager: 'warning',
        user: 'info'
      }
      return types[role] || 'info'
    }

    const getRoleText = (role) => {
      const texts = {
        admin: '管理员',
        manager: '经理',
        user: '普通用户'
      }
      return texts[role] || role
    }

    const getPermissionText = (permission) => {
      const texts = {
        dashboard: '数据总览',
        category: '分类分析',
        price: '价格分析',
        query: '数据查询',
        monitor: '系统监控',
        user: '用户管理',
        spider: '爬虫控制',
        export: '数据导出'
      }
      return texts[permission] || permission
    }

    onMounted(() => {
      fetchUsers()
      fetchRoles()
      fetchLoginLogs()
    })

    return {
      loading,
      searchKeyword,
      users,
      roles,
      loginLogs,
      userDialogVisible,
      roleDialogVisible,
      isEdit,
      userForm,
      roleForm,
      userRules,
      filteredUsers,
      showAddUserDialog,
      editUser,
      saveUser,
      toggleUserStatus,
      deleteUser,
      editRole,
      saveRole,
      handleSearch,
      getRoleType,
      getRoleText,
      getPermissionText
    }
  }
}
</script>

<style scoped>
.user-management {
  height: 100vh;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-content h1 {
  margin: 0;
  color: #303133;
}

.el-main {
  padding: 20px;
  background-color: #f5f5f5;
}

.user-list {
  margin-bottom: 20px;
}

.role-management {
  margin-bottom: 20px;
}

.login-logs {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style> 